﻿using MongoFramework.Linq;
using Zhaoxi.MongoDBSample.Data;
using Zhaoxi.MongoDBSample.Models;

namespace Zhaoxi.MongoDBSample.Respositories
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly SchoolDbContext _schoolDbContext;

        public BaseRepository(SchoolDbContext schoolDbContext)
        {
            _schoolDbContext = schoolDbContext;
        }

        public async Task<IEnumerable<T>> GetAllAsync()
        {
            var result = await _schoolDbContext.Set<T>().ToListAsync();
            return result;
        }

        public async Task<T?> GetByIdAsync(string id)
        {
            var result = await _schoolDbContext.Set<T>().FindAsync(id);
            return result;
        }

        public async Task<T> CreateAsync(T entity)
        {
            _schoolDbContext.Set<T>().Add(entity);
            await _schoolDbContext.SaveChangesAsync();
            return entity;
        }

        public async Task<T> UpdateAsync(T entity)
        {
            _schoolDbContext.Set<T>().Update(entity);
            await _schoolDbContext.SaveChangesAsync();
            return entity;
        }

        public async Task DeleteAsync(T entity)
        {
            _schoolDbContext.Set<T>().Remove(entity);
            await _schoolDbContext.SaveChangesAsync();
        }
    }
}
